<?php

namespace App\Http\Controllers\home\user;

use App\Http\Controllers\home\PayController;
use App\Models\Product;
use App\Models\Sender;
use App\Models\Wxpay_js;
use App\Org\wxpay\WXTool;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\User;
use App\Models\User_info;
use App\Models\Doctor;
use App\Models\District;
use App\Models\Address;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Order_info;
use App\Models\Order_time;
use App\Models\Comment;
use App\Models\Coupon;

class OrderController extends Controller
{
    public function order($id)
    {
        $order = new Order();
        $bo = $order->firstorder($id);
        $order_info = new Order_info();
        $list_info = $order_info->listorder($id);
        $order_time = new Order_time();
        $list_time = $order_time->seltime($id);
        $phone = Sender::where('id', $bo->sender_id)->first();
        if ($bo) {
            return view('home.user.order', ['phone' => $phone, 'list' => $bo, 'list_info' => $list_info, 'list_time' => $list_time]);
        } else {
            return redirect()->back();
        }

    }

    public function orderlist($id)
    {
        $status = [1 => '待付款', 2 => '待发货', 3 => '待收货', 4 => '待评价', 5 => '已完成', 6 => '已取消',];
        switch ($id) {
            case 1:
                $order = new Order();
                $row = $order->ordersta(1);
                if ($row) {

                    foreach ($row as $v) {
                        $order_info = new Order_info();
                        $list_info[$v->id] = $order_info->listorder($v->id);
                    }
//                    dd($list_info);

                    return view('home.user.orderlist', ['title' => '待付款', 'list' => $row, 'list_info' => $list_info, 'status' => $status]);
                } else {
                    return view('home.user.orderlist', ['title' => '待付款', 'list' => null]);
                }
                break;
            case 2:
                $order = new Order();
                $row = $order->ordersta(2);
                if ($row) {
                    foreach ($row as $v) {
                        $order_info = new Order_info();
                        $list_info[$v->id] = $order_info->listorder($v->id);
                    }
                    return view('home.user.orderlist', ['title' => '待发货', 'list' => $row, 'list_info' => $list_info, 'status' => $status]);
                } else {
                    return view('home.user.orderlist', ['title' => '待发货', 'list' => null]);
                }
                break;
            case 3:
                $order = new Order();
                $row = $order->ordersta(3);
                if ($row) {
                    foreach ($row as $v) {
                        $order_info = new Order_info();
                        $list_info[$v->id] = $order_info->listorder($v->id);
                    }
                    return view('home.user.orderlist', ['title' => '待收货', 'list' => $row, 'list_info' => $list_info, 'status' => $status]);
                } else {
                    return view('home.user.orderlist', ['title' => '待收货', 'list' => null]);
                }
                break;
            case 4:
                $order = new Order();
                $row = $order->ordersta(4);
                if ($row) {
                    foreach ($row as $v) {
                        $order_info = new Order_info();
                        $list_info[$v->id] = $order_info->listorder($v->id);
                    }
                    return view('home.user.orderlist', ['title' => '待评价', 'list' => $row, 'list_info' => $list_info, 'status' => $status]);
                } else {
                    return view('home.user.orderlist', ['title' => '待评价', 'list' => null]);
                }
                break;
            case 5:
                $order = new Order();
                $row = $order->orderwq();
                if ($row) {
                    foreach ($row as $v) {
                        $order_info = new Order_info();
                        $list_info[$v->id] = $order_info->listorder($v->id);
                    }
                    return view('home.user.orderlist', ['title' => '已完成', 'list' => $row, 'list_info' => $list_info, 'status' => $status]);
                } else {
                    return view('home.user.orderlist', ['title' => '已完成', 'list' => null]);
                }
                break;
            case 8:
                $order = new Order();
                $row = $order->userorder();
                if ($row) {
                    foreach ($row as $v) {
                        if ($v->status != 7) {
                            $order_info = new Order_info();
                            $list_info[$v->id] = $order_info->listorder($v->id);
                        }
                    }
                    return view('home.user.orderlist', ['title' => '全部订单', 'list' => $row, 'list_info' => $list_info, 'status' => $status]);
                } else {
                    return view('home.user.orderlist', ['title' => '全部订单', 'list' => null]);
                }
                break;
        }
    }

    //订单生成页面
    public function suborder($id = 0)
    {
        $user_id = session('homeuser');
        $address = new Address();
        $addrow = $address->addselect($user_id);
        if ($id == 0) {
            $cart = new Cart();
            $cartrow = $cart->selPitch();
            if ($cartrow == null) {
                return redirect()->back()->with('cart', 'cart');
            } else {
                $sum = 0;
                foreach ($cartrow as $v) {
                    $sum += $v->price * $v->count;
                }
                $coupon = new Coupon();
                $cou = $coupon->selectCoupon($sum);
                return view('home.user.suborder', ['addrow' => $addrow, 'cartrow' => $cartrow, 'cou' => $cou, 'sum' => $sum]);
            }
        } else {
            $product = new Product();
            $cartrow[0] = $product->selFirst($id);
            $cartrow[0]->count = 1;
            $coupon = new Coupon();
            $cou = $coupon->selectCoupon($cartrow[0]->price);
//            dd($cartrow);
            return view('home.user.suborder', ['addrow' => $addrow, 'cartrow' => $cartrow, 'cou' => $cou, 'sum' => $cartrow[0]->price]);
        }


    }

    //将所有地址的默认都变为1
    public function changesta()
    {
        $user_id = session('homeuser');
        Address::where('user_id', $user_id)->where('status', '2')->update(['status' => 1]);
    }

    //订单里面的修改默认地址
    public function updatedizhi($id)
    {
        $this->changesta();
        $address = Address::find($id);
        $address->status = 2;
        $address->save();
        return redirect('/home/user/order/suborder');
    }

    //保存订单信息，并跳转到支付页面
    public function insorder(Request $request, $id = 0)
    {
        //查询当前用户选中的地址
        $address = new Address();
        $ress = $address->selectAdd();
        //判断不同情况
        if ($id == 0) {
            //查询订单总金额
            $cart = new Cart();
            $amount = $cart->sumCart();
        } else {
            //查询订单总金额
            $product = new Product();
            $cartrow = $product->selFirst($id);
            $amount = $cartrow->price;
        }

        //查找满足订单总金额的优惠券
        $coupon = new Coupon();
        $cou = $coupon->selectCoupon($amount);
        $discount = 0;
        $coup_id=$request->input('discount');
        if($coup_id!=0){
            if ($cou) {
                foreach ($cou as $v) {
                    if ($v->id == $coup_id) {
                        $discount = $v->value;
                        $cou_id = $v->id;
                    }
                }
                if ($cou_id == $coup_id) {
                    //将优惠卷的状态变为已经使用
                    $coupons = Coupon::find($cou_id);
                    $coupons->status = 2;
                    $coupons->usetime=time();
                    $coupons->useinfo='购买了';
                    $coupons->save();
                }
            }
        }
        //判断运费
        $carriage = $amount >= 20 ? 0 : 10;
        //判断实付款
        $realpay = $amount - $discount + $carriage;
        //生成一个订单对象
        $order = new Order();
        $number = time() . rand(1000, 9999);
        $order->user_id = session('homeuser');
        $order->store_id = session('location')['store_id'];
        $order->amount = $amount;//订单总金额
        $order->discount = $discount;//优惠金额
        $order->carriage = $carriage;//运费
        $order->realpay = $realpay;//实付款

        $order->paymethod = $request->input('paymethod');//支付方式

        $order->status = 1; //状态未付款
        $order->number = $number;//订单编号
        $order->remark = $request->input('remark'); //备注
        //插入地址信息
        $order->name = $ress->name;
        $order->phone = $ress->phone;
        $order->address = $ress->city . $ress->detail;
        //插入信息生成订单
        $order->save();

        //得到订单id
        $order_id = $order->id;
        //插入生成订单时间
        $order_time = new Order_time();
        $order_time->order_id = $order->id;
        $order_time->save();

        if ($id == 0) {
            //将购物车中被选中的商品信息存到订单详情表里
            $cart = new Cart();
            $row = $cart->selPitch();

        } else {
            $row[0] = $cartrow;
        }

        foreach ($row as $v) {
            $order_info = new Order_info();
            $order_info->order_id = $order_id;
            if ($id != 0) {
                $order_info->product_id = $id;
                $order_info->count = 1;
            } else {
                $order_info->product_id = $v->product_id;
                $order_info->count = $v->count;
            }

            $order_info->name = $v->name;
            $order_info->preview = $v->preview;
            $order_info->price = $v->price;
            $order_info->specifications = $v->specifications;
            $order_info->save();
        }
        if ($id == 0) {
            //删除购物车中被选中的商品信息
            $delcart = new Cart();
            $m = $delcart->delPitch();
        }

        return redirect('home/user/order/payorder?number=' . $number);
    }

    //订单结算
    public function payorder(Request $request)
    {
        $openid = $request->session()->get('openid', '');
        if($openid==''){
            return "openid 已经过期！";
        }
        $wxp = $this->wx_js();
        if ($request->input('number') != "") {
            $res = Order::where('number', $request->input('number'))->where('status', '1')->first();
        } else {
            $res = Order::where('status', '1')->first();
        }
        $price = $res->realpay * 100;
        $ob = WXTool::wxPayData($res->name, $res->number, 1, $openid);

        return view('home.user.payorder', ['res' => $res, 'wxp' => $wxp, 'ob' => $ob]);
    }

    //取消订单
    public function cancelorder($id)
    {
        $order = new Order();
        $bo = $order->cancelorder($id);
        if($bo){
            return redirect('/home/user/order/orderlist/1')->with('msg','6');
        }else{
            return redirect('/home/user/order/orderlist/1');
        }
    }

    //删除订单
    public function deleteorder($id)
    {
        $order = new Order();
        $bo = $order->deleteorder($id);
        if($bo){
            return redirect('/home/user/order/orderlist/5')->with('msg','7');
        }else{
            return redirect()->back();
        }
    }

    //跳转到评价页面
    public function evaluate($id)
    {
        $order_info = new Order_info();
        $list_info = $order_info->listorder($id);
        if ($list_info) {
            return view('home.user.evaluate', ['list' => $list_info]);
        } else {
            return redirect()->back();
        }

    }

    //评价
    public function evaluateorder(Request $request)
    {
        $id = session('homeuser');
        $data = $request->only('product_id', 'content', 'level');
        $order_id = $request->input('order_id');
        $order = Order::find($order_id);
        $order->status = 5;
        $order->save();
        foreach ($data['product_id'] as $k => $v) {
            $comment = new Comment();
            $comment->user_id = $id;
            $comment->product_id = $v;
            $comment->content = $data['content'][$k];
            $comment->level = $data['level'][$k];
            $comment->save();
        }
        return redirect('/home/user/order/orderlist/5')->with('msg', '4');
    }

    public function wx_js()
    {
        //JSSDK 相关
        $access_tonken = WXTool::getAccessToken();
        $jsapi_ticket = WXTool::getJsApiTicket($access_tonken);
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $nonceStr = WXTool::createNonceStr();
        $timestamp = time();
        $signature = WXTool::signature($jsapi_ticket, $nonceStr, $timestamp, $url);
        //返回微信参数
        $ob = new Wxpay_js;
        $ob->appid = config('wxpay.APPID');
        $ob->timestamp = $timestamp;
        $ob->nonceStr = $nonceStr;
        $ob->signature = $signature;
        return $ob;
    }
}
